package com.ruoyi.common.encrypt;

import org.apache.commons.codec.binary.Base64;

import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 生成RSA密钥对
 * @Author: 黄龙
 * @Date: 2022/11/17 15:32
 */
public class RSAKeyGenerator {

    /**
     * 加密算法
     */
    public static final String RSA_ALGORITHM = "RSA";

    /**
     * 公钥key
     */
    private static final String PUBLIC_KEY = "publicKey";

    /**
     * 私钥KEY
     */
    private static final String PRIVATE_KEY = "privateKey";

    /**
     * APPID
     */
    private static final String APPID = "appId";

    /**
     * 生成公钥和私钥
     *
     * @param keySize
     * @return
     */
    public static Map<String, String> createKeys(int keySize) {
        //为RSA算法创建一个KeyPairGenerator对象
        KeyPairGenerator kpg;
        try {
            kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");
        }

        //初始化KeyPairGenerator对象,密钥长度
        kpg.initialize(keySize);
        //生成密匙对
        KeyPair keyPair = kpg.generateKeyPair();
        //得到公钥
        Key publicKey = keyPair.getPublic();
        String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded());
        //得到私钥
        Key privateKey = keyPair.getPrivate();
        String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded());
        Map<String, String> keyPairMap = new HashMap();
        keyPairMap.put(PUBLIC_KEY, publicKeyStr);
        keyPairMap.put(PRIVATE_KEY, privateKeyStr);
        keyPairMap.put(APPID, UUID.randomUUID().toString());

        return keyPairMap;
    }


    /**
     * 生成公钥和私钥
     * @param args
     */
    public static void main(String[] args) {
        Map<String, String> keyMap = RSAKeyGenerator.createKeys(1024);
        String publicKey = keyMap.get(PUBLIC_KEY);
        String privateKey = keyMap.get(PRIVATE_KEY);
        String appId = keyMap.get(APPID);
        System.out.println("公钥: " + publicKey);
        System.out.println("私钥： " + privateKey);
        System.out.println("appId： " + appId);

    }
}
